<script setup>
import { EmailOutlined } from "@vicons/material";
import { onBeforeUnmount, reactive, ref } from "vue";
import { disabledBtn } from "@/utils/disabledBtn";
import noteServeRequest from "@/utils/request";
import userApi from '@/utils/api/userApi'
import mailApi from '@/utils/api/mailApi'

// 自定义的事件名称
const emits = defineEmits("changeWindow");

const buttonObj = reactive({
    text: "获取验证码",
    time: 60,
    disabled: false,
    interval: null,
});

// 倒计时按钮
const runDownTime = () => {
    buttonObj.interval = setInterval(() => {
        if (buttonObj.time === 0) {
            // 倒计时结束
            clearInterval(buttonObj.interval); // 清除计划任务
            buttonObj.time = 60;
            buttonObj.text = "获取验证码";
            buttonObj.disabled = false;
            buttonObj.interval = null;
        } else {
            // 处于倒计时中
            buttonObj.time -= 1;
            buttonObj.text = buttonObj.time + "s 后重新获取";
            buttonObj.disabled = true;
        }
    }, 1000);
};

// 查询验证码的 key 值
const mailVcKey = ref(null);

// 获取注册的验证码
const getRegisterVc = async () => {
    // 判断是否为邮箱格式
    await registerFormRef.value?.validate(errors => {
        if (errors) throw "不符合邮箱格式";
    }, rule => rule?.key === "mail-empty" || rule?.key === "mail")

    // 按钮倒计时
    runDownTime()

    // 请求 API
    let mailRegisterVCAPI = { ...mailApi.mailRegisterVC }
    // 请求参数
    mailRegisterVCAPI.data = { mail: registerFormValue.account }
    // 发送请求
    noteServeRequest(mailRegisterVCAPI).then(response => {
        if (!response) return;
        mailVcKey.value = response.data; // 保存查询验证码的 key 值
    })
}

// 注册表单值
const registerFormValue = reactive({
    account: "", // 账号
    vc: "", // 验证码
    trim: false, // 是否勾选条款与协议
});

// 注册验证规则
const registerRules = {
    account: [
        {
            key: "mail-empty",
            required: true,
            message: "请输入邮箱账号！",
            trigger: "input",
        },
        {
            key: "mail",
            message: "请输入正确的邮箱账号！",
            validator: (rule, value) => {
                return /^[A-Za-z0-9]+([-._][A-Za-z0-9]+)*@[A-Za-z0-9]+(-[A-Za-z0-9]+)*(\.[A-Za-z]{2,6}|[A-Za-z]{2,4}\.[A-Za-z]{2,3})$/.test(
                    value
                );
            },
            trigger: "input",
        },
    ],
    vc: {
        required: true,
        message: "请输入验证码！",
        trigger: "input",
    },
    trim: {
        message: "请认证阅读本公司的条款与协议",
        validator: (rule, value) => {
            return !!value;
        },
        trigger: "change",
    },
};

// 注册表单组件实例
const registerFormRef = ref(null);

const registerBtnDisabled = ref(false); // 注册按钮是否被禁用

// 去注册
const toRegister = async () => {
    // 验证注册的表单
    await registerFormRef.value?.validate((errors) => {
        if (errors) throw "注册表单验证失败"
    });

    // 判断是否为获取验证码
    let vcKey = mailVcKey.value
    if (!vcKey) throw message.error("请先获取验证码")

    // 判断输入的邮箱和接收验证码的邮箱是否一致
    let vc_email = vcKey.split(":")[1] // 接收验证码的邮箱
    let email = registerFormValue.account // 注册账号的邮箱
    if (vc_email !== email)
        throw message.error("注册邮箱发生改变，请重新获取验证码")

    // 禁用注册的按钮
    disabledBtn(registerBtnDisabled, true)

    // 请求 API
    let mailRegisterAPI = { ...userApi.mailRegister }
    // 请求参数
    mailRegisterAPI.data = {
        email: registerFormValue.account,
        vc: registerFormValue.vc,
        vcKey: mailVcKey.value,
    }
    // 发送请求
    noteServeRequest(mailRegisterAPI).then(response => {
        if (!response) throw disabledBtn(registerBtnDisabled, false, true, 2.5); // 2.5 秒后解除禁用的注册按钮;
        emits("changeWindow", 3); // 跳转至注册成功界面
    })
}

// 组件销毁之前
onBeforeUnmount(() => {
    // 如果有计划任务，则清除
    if (buttonObj.interval) {
        clearInterval(buttonObj.interval);
    }
});
</script>

<template>
    <n-card>
        <!-- 注册标题 -->
        <n-space align="center" justify="space-between">
            <h2>注册</h2>
            <n-text>
                已有账号？
                <n-button text type="info" @click="emits('changeWindow', 1)">
                    前往登录
                </n-button>
            </n-text>
        </n-space>

        <!-- 注册表单 -->
        <n-form ref="registerFormRef" :model="registerFormValue" :rules="registerRules">
            <!-- 邮箱输入框 -->
            <n-form-item first label="邮箱" path="account">
                <n-input placeholder="请输入邮箱账号" v-model:value="registerFormValue.account">
                    <template #prefix>
                        <n-icon :size="20" :component="EmailOutlined" />
                    </template>
                </n-input>
            </n-form-item>

            <n-grid :cols="2" :x-gap="16">
                <n-form-item-gi label="验证码" path="vc">
                    <n-input placeholder="输入验证码" v-model:value="registerFormValue.vc" />
                </n-form-item-gi>
                <n-form-item-gi>
                    <n-button block secondary type="success" :disabled="buttonObj.disabled" @click="getRegisterVc">
                        {{ buttonObj.text }}
                    </n-button>
                </n-form-item-gi>
            </n-grid>

            <!-- 同意条款复选框 -->
            <n-form-item :show-label="false" path="trim">
                <n-checkbox v-model:checked="registerFormValue.trim">
                    <n-text>
                        同意本公司的
                        <n-button text type="info">
                            《条款与协议》
                        </n-button>
                    </n-text>
                </n-checkbox>
            </n-form-item>

            <n-button block type="success" :disabled="registerBtnDisabled" @click="toRegister">
                注册
            </n-button>
        </n-form>
    </n-card>
</template>